package com.kangjia.model.service;

import java.util.ArrayList;
import java.util.List;

public abstract class TreeService<T> {

	public T createRoot(List<T> entities) {
		return createRoot(entities, null);
	}

	public T createRoot(List<T> entities, List<Integer> ids) {
		T root = createT();
		List<T> cps = new ArrayList<>(entities);
		List<T> clear = new ArrayList<>();
		for (T entity : entities) {
			judge(ids, entity);
			expand(entity, true);
			Integer entityId = getId(entity);
			if (getParent(entity) == null) {
				addChildren(root, entity);
			}
			for (T node : cps) {
				if (getParent(node) != null && getParent(node).equals(entityId)) {
					addChildren(entity, node);
					clear.add(node);
				} else if (getParent(node) == null) {
					clear.add(node);
				}
			}
			cps.removeAll(clear);
			clear.clear();
		}
		return root;
	}

	private void judge(List<Integer> ids, T entity) {
		if (ids != null) {
			if (ids.contains(getId(entity))) {
				checked(entity, true);
			} else {
				checked(entity, false);
			}
		}
	}

	public abstract T createT();

	public abstract Integer getId(T entity);

	public abstract Integer getParent(T entity);

	public abstract void addChildren(T entity, T node);

	public abstract void checked(T entity, boolean is);

	public abstract void expand(T entity, boolean is);
}
